package com.itany.shop.service.proxy;

import com.itany.shop.entity.User;
import com.itany.shop.exception.*;
import com.itany.shop.factory.ObjectFactory;
import com.itany.shop.service.UserService;
import com.itany.shop.tran.TransactionManager;
import org.apache.commons.fileupload.FileItem;

import javax.servlet.http.HttpSession;

/**
 * @author 石小俊
 * @date 2023年07月05日 16:58
 */
public class UserServiceProxy implements UserService {

    private TransactionManager tran = (TransactionManager) ObjectFactory.getObject("tran");
    private UserService userService = (UserService) ObjectFactory.getObject("userServiceTarget");

    @Override
    public void register(String username, String password, String phone, String address) throws RequestParameterErrorException, UserExistException {
        try {
            tran.begin();
            userService.register(username,password,phone,address);
            tran.commit();
        } catch (RequestParameterErrorException e) {
            tran.rollback();
            throw e;
        } catch (UserExistException e) {
            tran.rollback();
            throw e;
        }
    }

    @Override
    public void register(String username, String password, String phone, String address, FileItem file, HttpSession session) throws RequestParameterErrorException, UserExistException, FileUploadErrorException {
        try {
            tran.begin();
            userService.register(username,password,phone,address,file,session);
            tran.commit();
        } catch (RequestParameterErrorException e) {
            tran.rollback();
            throw e;
        } catch (UserExistException e) {
            tran.rollback();
            throw e;
        } catch (FileUploadErrorException e){
            tran.rollback();
            throw e;
        }
    }

    @Override
    public User login(String username, String password, String code, String image) throws RequestParameterErrorException, CodeErrorException, UserNotExistException {
        try {
            tran.begin();
            User user = userService.login(username,password,code,image);
            tran.commit();
            return user;
        } catch (RequestParameterErrorException e) {
            tran.rollback();
            throw e;
        } catch (CodeErrorException e) {
            tran.rollback();
            throw e;
        } catch (UserNotExistException e) {
            tran.rollback();
            throw e;
        }
    }
}
